package cn.edu.zisu.auth.controller;

import cn.edu.zisu.auth.LoginApi;
import cn.edu.zisu.auth.model.LoginParam;
import cn.edu.zisu.auth.model.UserDTO;
import cn.edu.zisu.auth.service.AuthService;
import cn.edu.zisu.common.model.enumeration.ResponseCodeEnum;
import cn.edu.zisu.common.model.request.RequestParameter;
import cn.edu.zisu.common.model.response.EntityResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Optional;


@Validated
@RestController
@RequiredArgsConstructor
public class LoginController implements LoginApi {

    private final HttpSession httpSession;

    @Autowired
    private final AuthService authService;

    @Override
    public EntityResponse loginByAccountAndPassword(RequestParameter<LoginParam> loginParam) {
        Optional<UserDTO> userDTO = authService.loginByAccountAndPassword(loginParam.getBody());

        if(!userDTO.isPresent()){
            return new EntityResponse<>(ResponseCodeEnum.FORBIDDEN,"",null);
        }
        final UserDTO user = userDTO.get();
        httpSession.setAttribute("uid", user.getAccount());
        httpSession.setAttribute("uname", user.getName());
        return new EntityResponse<>(ResponseCodeEnum.SUCCESS, "登录成功", user);
    }
}
